package com.beyondsoft.mcms.web;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.beyondsoft.mcms.common.Constants;
import com.beyondsoft.mcms.domain.Advice;
import com.beyondsoft.mcms.domain.Conference;
import com.beyondsoft.mcms.domain.GroupInfo;
import com.beyondsoft.mcms.domain.Item;
import com.beyondsoft.mcms.domain.MemberInfo;
import com.beyondsoft.mcms.domain.Menus;
import com.beyondsoft.mcms.domain.Users;

@RequestMapping("/menuses")
@Controller
@RooWebScaffold(path = "menuses", formBackingObject = Menus.class, create = false, delete = false, update = false)
@RooWebFinder
public class MenusController {

    @RequestMapping(params = "validUsername")
    public String validUsername(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String username = request.getParameter("validUsername");
        List<Users> users = Users.findUsersesByUsernameEquals(username).getResultList();
        if (users != null && users.size() > 0) {
            response.getWriter().print("invalid");
        } else {
            response.getWriter().print("valid");
        }
        return null;
    }

    @RequestMapping(params = "validMemberName")
    public String validMemberName(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String memberName = request.getParameter("validMemberName");
        List<MemberInfo> memberinfoes = MemberInfo.findMemberInfoesByMemberNameEquals(memberName).getResultList();
        if (memberinfoes != null && memberinfoes.size() > 0) {
            response.getWriter().print("invalid");
        } else {
            response.getWriter().print("valid");
        }
        return null;
    }

    @RequestMapping(value = "/{id}", params = "validMemberName")
    public String validMemberName(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String memberName = request.getParameter("validMemberName");
        String currentName = MemberInfo.findMemberInfo(id).getMemberName();
        if (currentName.equals(memberName)) {
            response.getWriter().print("valid");
            return null;
        }
        List<MemberInfo> memberinfoes = MemberInfo.findMemberInfoesByMemberNameEquals(memberName).getResultList();
        if (memberinfoes != null && memberinfoes.size() > 0) {
            response.getWriter().print("invalid");
        } else {
            response.getWriter().print("valid");
        }
        return null;
    }

    @RequestMapping(params = "validConferenceName")
    public String validConferenceName(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String conferenceName = request.getParameter("validConferenceName");
        List<Conference> conferences = Conference.findConferencesByNameEquals(conferenceName).getResultList();
        if (conferences != null && conferences.size() > 0) {
            response.getWriter().print("invalid");
        } else {
            response.getWriter().print("valid");
        }
        return null;
    }

    @RequestMapping(value = "/{id}", params = "validConferenceName")
    public String validConferenceName(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String conferenceName = request.getParameter("validConferenceName");
        String currentName = Conference.findConference(id).getName();
        if (currentName.equals(conferenceName)) {
            response.getWriter().print("valid");
            return null;
        }
        List<Conference> conferences = Conference.findConferencesByNameEquals(conferenceName).getResultList();
        if (conferences != null && conferences.size() > 0) {
            response.getWriter().print("invalid");
        } else {
            response.getWriter().print("valid");
        }
        return null;
    }

    @RequestMapping(params = "getGroupMembers")
    public String getGroupMembers(@RequestParam("getGroupMembers") GroupInfo groupinfo, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // String groupId = request.getParameter("getGroupMembers");
        // GroupInfo groupinfo = GroupInfo.findGroupInfo(Long.valueOf(groupId));
        Set<Item> businesstypes = groupinfo.getBusinessTypes();
        Set<Item> positiontypes = groupinfo.getPositionTypes();
        List<Long> businessIds = new ArrayList<Long>(), positionTypeIds = new ArrayList<Long>();
        for (Iterator<Item> it = businesstypes.iterator(); it.hasNext(); ) {
            Item item = (Item) it.next();
            if (item.getIsValid()) {
                businessIds.add(item.getId());
            }
        }
        for (Iterator<Item> it = positiontypes.iterator(); it.hasNext(); ) {
            Item item = (Item) it.next();
            if (item.getIsValid()) {
                positionTypeIds.add(item.getId());
            }
        }
        List<MemberInfo> memberinfoList = new ArrayList<MemberInfo>();
        if (businesstypes.size() == 0 && positionTypeIds.size() == 0) {
            memberinfoList = MemberInfo.findAllMemberInfoes();
        } else {
            memberinfoList = MemberInfo.findMemberInfoesByBusinessTypeInAndPositionTypeIn(businessIds, positionTypeIds).getResultList();
        }
        if (memberinfoList != null && memberinfoList.size() > 0) {
            StringBuffer returnStr = new StringBuffer("");
            for (int i = 0; i < memberinfoList.size(); i++) {
                MemberInfo member = memberinfoList.get(i);
                if (i != 0) {
                    returnStr.append(",");
                }
                returnStr.append(member.getId() + ":" + member.getMemberName());
            }
            response.getWriter().print(returnStr.toString());
        }
        return null;
    }

    @RequestMapping(params = { "sendType", "conference" })
    public String getReceivers(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String sendType = request.getParameter("sendType");
        String conferenceId = request.getParameter("conference");
        Conference conference = Conference.findConference(Long.valueOf(conferenceId));
        StringBuffer receivers = new StringBuffer("");
        List<Advice> advices = Advice.findAdvicesByConferenceAndMemberInfo(conference, null).getResultList();
        for (int i = 0; i < advices.size(); i++) {
            Advice advice = advices.get(i);
            MemberInfo memberInfo = advice.getMemberInfo();
            if (i != 0) {
                receivers.append(",");
            }
            receivers.append(memberInfo.getMemberName());
        }
        /*
         * if (Long.valueOf(sendType) == Constants.MESSAGE_TYPE_MAIL){ for (int
         * i=0; i<advices.size(); i++) { Advice advice = advices.get(i);
         * MemberInfo memberInfo = advice.getMemberInfo(); String delegateEmail
         * = memberInfo.getDelegateEmail(); String contactEmail =
         * memberInfo.getContactEmail(); if (i != 0){ receivers.append(","); }
         * receivers.append(contactEmail); receivers.append(",");
         * receivers.append(delegateEmail); } }else if (Long.valueOf(sendType)
         * == Constants.MESSAGE_TYPE_SMS){ for (int i=0; i<advices.size(); i++)
         * { Advice advice = advices.get(i); MemberInfo memberInfo =
         * advice.getMemberInfo(); String delegate =
         * memberInfo.getDelegateMobile(); String contact =
         * memberInfo.getContactMobile(); if (i != 0){ receivers.append(","); }
         * receivers.append(contact); receivers.append(",");
         * receivers.append(delegate); } }else { for (int i=0; i<advices.size();
         * i++) { Advice advice = advices.get(i); MemberInfo memberInfo =
         * advice.getMemberInfo(); String delegateMM =
         * memberInfo.getDelegateMicroMessage(); String contactMM =
         * memberInfo.getContactMicroMessage();
         *
         * if (delegateMM!=null && delegateMM.trim().length()>0){ if
         * (receivers.length() > 0){ receivers.append(","); }
         * receivers.append(delegateMM); } if (contactMM!=null &&
         * contactMM.trim().length()>0){ if (receivers.length() > 0){
         * receivers.append(","); } receivers.append(contactMM); } } }
         */
        response.getWriter().print(receivers.toString());
        receivers.setLength(0);
        return null;
    }

    @RequestMapping(value = "getMsgContent", params = { "conference", "sendType", "smsTemplate" })
    public String getMsgContent(Conference conference, HttpServletRequest request, HttpServletResponse response) throws Exception {
        long sendType = Long.valueOf(request.getParameter("sendType"));
        int smsTemplate = Integer.valueOf(request.getParameter("smsTemplate"));
        
        String conferenceName = conference.getName();
        String addr = conference.getPlace();
        String time = new SimpleDateFormat("yyyy年MM月dd日 ").format(conference.getHoldDate()) + conference.getHoldTime();
        String endDay = new SimpleDateFormat("yyyy年MM月dd日 ").format(conference.getRegistrationEndTime());
        
        String contentTemplate = "";
        if (sendType == Constants.MESSAGE_TYPE_MAIL){
	        contentTemplate = "<div><br/>各会员单位：<br/>" + "现举办" + conferenceName + "活动，<br/>" + conference.getDescription() + "<br/><br/>此致<br/>" + "深圳市金融信息服务协会<br/>" + "电话：0755-82427325、0755-82265770<br/>" + "地址：中国深圳市银湖路金湖一街CDI大厦  邮编：518029<br/></div>";
	        response.getWriter().print(contentTemplate);
	        return null;
	        
        } else if (sendType == Constants.MESSAGE_TYPE_SMS){
        	if (smsTemplate == 0){
        		contentTemplate = "<div><br/>我会定于" +time+"（时间）在"+addr+"(地点)召开"+conferenceName+"（活动），现将有关事项通知如下：<font color='red'>XXXX</font>。<br/> </div>";
    	        response.getWriter().print(contentTemplate);
        		
        	} else if (smsTemplate == 1){
        		contentTemplate = "<div><br/>原定于"+time+"（时间）在"+addr+"(地点)召开的"+conferenceName+"（活动），因<font color='red'>XXXX</font>原因暂时取消，给您造成的不便请谅解，<font color='red'>XXXX</font>时间另行通知，谢谢。<br/> </div>";
    	        response.getWriter().print(contentTemplate);
        		
        	} else if (smsTemplate == 2){
        		contentTemplate = "<div><br/>拟于"+time+"（时间）在"+addr+"(地点)召开的"+conferenceName+"（活动），网上报名时间截止至"+endDay+"（时间），请您登陆会员管理系统报名参与，期待您的到来，谢谢。<br/></div>";
    	        response.getWriter().print(contentTemplate);
        	}
        	
        	return null;
        }
        
        return null;
    }
}
